package com.whut.f2f.chat;

import com.whut.f2f.chat.connector.Connector;
import com.whut.f2f.chat.connector.DefaultConnector;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 聊天服务端
 *
 * Created by null on 2017/1/20.
 */
public class ChatServer {

    // 分割符
    private static final String DELIMITER = "$_$";
    // 最大长度
    private static final int MAX_LENGTH = 1024;

    private final Connector connector = new DefaultConnector();

    /**
     * 服务端绑定端口号
     *
     * @param port 端口号
     */
    public void bind(int port) {
        // 配置服务端的nio线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
                            ChatServerHandler handler = new ChatServerHandler();
                            handler.setConnector(connector);
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_LENGTH, delimiter))
                                         .addLast(new StringDecoder())
                                         .addLast(new StringEncoder())
                                         .addLast(handler);
                        }
                    });
            // 绑定端口，同步等待成功
            ChannelFuture future = bootstrap.bind(port).sync();
            // 等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
